package com.comet;

import java.io.Serializable;
import java.util.HashMap;
import java.util.Map;
import java.util.Map.Entry;

import javax.servlet.http.HttpServletRequest;

import org.auto.comet.ErrorHandler;
import org.auto.comet.PushException;
import org.auto.comet.Socket;
import org.auto.comet.SocketHandler;

public class CometSocketHandler implements SocketHandler{

	//private ChatRoomService chatRoomService;

    private Map<Serializable, Socket> socketMapping = new HashMap<Serializable, Socket>();

	public Map<Serializable, Socket> getSocketMapping() {
		return socketMapping;
	}

	@Override
	public boolean accept(Socket socket, HttpServletRequest request) {
		String userID = request.getParameter("userID");
		if (socketMapping.get(userID) != null) {
            return false;
          }
	    socket.setErrorHandler(new ErrorHandler() {

			@Override
			public void error(Socket socket, PushException e) {
				removeSocket(socket);
			}
	           
	    });
	    socketMapping.put(userID, socket);
	    return true;
	
	}

	@Override
	public void quit(Socket socket, HttpServletRequest request) {
		String userID = request.getParameter("userID");
		this.socketMapping.remove(userID);
	}
	
	private void removeSocket(Socket socket){
		 for (Entry<Serializable, Socket> entry : socketMapping.entrySet()) {
             Socket value = entry.getValue();
             if (value.equals(socket)) {
                     Serializable key = entry.getKey();
                     socketMapping.remove(key);
             }
     }

	}

}
